package just.stuff.morsels.ui.assist;

import just.stuff.morsels.MorselApplication;
import just.stuff.morsels.MorselSession;
import just.stuff.morsels.objects.AssistanceRequest;
import just.stuff.morsels.objects.Morsel;
import just.stuff.morsels.objects.User;

import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.AjaxLink;
import org.apache.wicket.markup.ComponentTag;
import org.apache.wicket.markup.MarkupStream;

public class GetAssistanceLink extends AjaxLink<Void> {

	private Morsel morsel;
	
	public GetAssistanceLink( String id, Morsel morsel) {
		super( id );
		this.morsel = morsel;
		setOutputMarkupId( true );
	}
	
	@Override
	public void onClick(AjaxRequestTarget target) {
		switch( getMode()) {
			case ASK: {
				AssistanceRequest req = new AssistanceRequest( MorselSession.get().getUser(), morsel );
				MorselApplication.dataSource().save( req );
				break;
			}
			case GIVE:
			case CANCEL: {
				AssistanceRequest req = MorselApplication.dataSource().getAssistance( morsel );
				MorselApplication.dataSource().delete( req );
				break;
			}
			default:
			
		}
		target.addComponent( this );
	}
	
	@Override
	protected void onComponentTagBody(MarkupStream markupStream,
			ComponentTag openTag) {
		String label = null;
		switch( getMode() ) {
			case ASK: label = "Request assistance"; break;
			case CANCEL: label = "Cancel assistance request"; break;
			case GIVE: label = "Close assistance request"; break;
			default:
		}
		replaceComponentTagBody(markupStream, openTag, label );
	}
	
	private  Mode getMode() {
		User user = MorselSession.get().getUser();
		if( user == null )
			return Mode.NONE;
		AssistanceRequest req = MorselApplication.dataSource().getAssistance( morsel );
		if( req == null )
			return Mode.ASK;
		return user.getId().equals( req.getFrom() ) ? Mode.CANCEL : Mode.GIVE;
	}
	
	@Override
	public boolean isVisible() {
		return getMode() != Mode.NONE;
	}
	
	public static enum Mode {
		NONE,
		ASK,
		CANCEL,
		GIVE;
	}
	
}
